<template>
  <div id="app" class="container">
    <div class="left-panel">
      <draggable v-model="items" group="items" item-key="name">
        <template #item="{ element }">
          <div class="item">
            <span>{{ element.name }}</span>
            <v-chart :options="element.data.options" :style="{ width: '100%', height: '200px' }" />
          </div>
        </template>
      </draggable>
    </div>
    <div class="right-panel">
      <h2>拖拽区域</h2>
      <draggable v-model="droppedItems" group="items" item-key="name" @end="handleDragEnd">
        <template #item="{ element }">
          <div class="dropped-item">
            <span>{{ element.name }}</span>
            <v-chart :options="element.data.options" :style="{ width: '100%', height: '200px' }" />
          </div>
        </template>
      </draggable>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import draggable from 'vuedraggable';
import VChart from 'vue-echarts';
import * as echarts from 'echarts/core';
import { LineChart, BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer,
]);

const items = ref([
  {
    name: 'Line Chart',
    data: {
      options: {
        title: { text: 'Line Chart Example' },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: { type: 'value' },
        series: [{
          name: 'Sales',
          type: 'line',
          data: [120, 200, 150, 80, 70, 110, 130],
        }],
      }
    },
  },
  {
    name: 'Bar Chart',
    data: {
      options: {
        title: { text: 'Bar Chart Example' },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: { type: 'value' },
        series: [{
          name: 'Sales',
          type: 'bar',
          data: [120, 200, 150, 80, 70, 110, 130],
        }],
      }
    },
  },
]);

const droppedItems = ref([]);

// 处理拖拽结束事件
const handleDragEnd = () => {
  nextTick(() => {
    const charts = document.querySelectorAll('.dropped-item v-chart');
    charts.forEach(chart => {
      chart.__echarts__ && chart.__echarts__.resize();
    });
  });
};

</script>

<style>
.container {
  display: flex;
  height: 100vh;
}

.left-panel {
  width: 30%;
  background: #f0f0f0;
  padding: 10px;
  overflow-y: auto;
}

.right-panel {
  flex: 1;
  padding: 10px;
  background: #ffffff;
}

.item, .dropped-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ccc;
  background: #fff;
  cursor: move;
}
</style>